<template>
  <div class="topbar">
    <!-- 版心 -->
    <div class="wrap topbarwarp">
      <!-- 左边标题 -->
      <div class="left">欢迎来到叩丁狼积分商城</div>
      <!-- 右侧用户信息导航 -->
      <ul class="right">
        <li>
          <img :src="userInfo.headImg" class="avatar" />
          用户名：{{ userInfo.nickName }}
        </li>
        <li>我的积分：{{ userInfo.coin }}</li>
        <li>获取积分</li>
        <li>叩丁狼官网</li>
        <!-- 购物车 -->
        <li class="cart-btn" v-if="isLogined">
          <img src="../assets/img/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>
        <li class="login-btn" v-else @click="changeIsShowModal(true)">登录</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState, mapActions } from "vuex";
import { wechatUsersAPI } from "@/request/api.js";
export default {
  methods: {
    ...mapMutations({
      // 登录框
      changeIsShowModal: "ShowModal/changeIsShowModal",
      // 登录状态
      changeIsShowLogin: "LoginState/changeIsShowLogin",
      // 初始化用户信息
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      // 提示组件
      asyncToast: "ShowToast/asyncToast",
      // 更新用户信息
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
  },
  computed: {
    //登录状态
    ...mapState({
      isLogined: (state) => state.LoginState.isLogined,
      // 用户信息
      userInfo: (state) => state.userInfo.userInfo,
      cartTotal: (state) => state.userInfo.cartTotal,
    }),
  },

  // 微信扫码
  created() {
    //等待路由加载完 获取临时票据
    this.$router.onReady(async () => {
      let pathCode = this.$route.query.code;
      // console.log("临时票据", pathCode);
      // 如果有临时票据才发 扫码登录请求
      if (pathCode) {
        // 发送扫码请求
        let req = await wechatUsersAPI({
          code: pathCode,
        });
        if (!req) return;
        // 扫码请求后有三种情况
        if (req.code == 0) {
          // 1.提示登录成功
          this.asyncToast({
            showToast: true,
            text: "登录成功!!",
            type: "success",
          });
          // 2.存储token值
          localStorage.setItem("x-auth-token", req["x-auth-token"]);
          // 3.改变登录状态
          this.changeIsShowLogin(true);
          // 4.清除 code，重定向
          this.$router.push(this.$route.path);

          // 更新用户信息
          this.asyncChangeUserInfo()
        }
        // code 过期
        else if (req.code == 400) {
          // 提示重新扫码
          this.asyncToast({
            showToast: true,
            text: "请重新扫码!!",
            type: "danger",
          });
          // 显示登录框
          this.changeIsShowModal(true);
        } else if (req.code == 407) {
          // a.提示首次微信登录需要绑定手机号码
          this.asyncToast({
            showToast: true,
            text: "首次微信扫码需先绑定手机号码!",
            type: "wran",
          });
          // b.存储 uuid
          localStorage.setItem("uuid", req.uuid);
          // c.清除地址栏临时票据code
          this.$router.push(this.$route.path);
          // d.自动打开登录框
          this.changeIsShowModal(true);
        }
      } else {
        // 组件重载
        let token = localStorage.getItem("x-auth-token");
        this.changeIsShowLogin(Boolean(token));

        // 根据token 更新用户信息
        if (token) {
          this.asyncChangeUserInfo();
        } else {
          this.initUserInfo();
        }
      }
    });
  },

  // 手动删除 token 更新登录状态
  // 方式一 ： watch 监听
  // watch: {
  //   "$route.path": {
  //     handler() {
  //       let token = localStorage.getItem("x-auth-token");
  //       // if (token) {
  //       //   this.changeIsShowLogin(true);
  //       // } else {
  //       //   this.changeIsShowLogin(false);
  //       // }
  //       this.changeIsShowLogin(Boolean(token)); //优化方案
  //     },
  //   },
  // },

  // 方式二 组件重载
  // 给Topbar加上key值 ，监听路径值 ，路径变化改变key值  组件重载更新登录状态
};
</script>

<style lang="less" scoped>
.topbar {
  height: 40px;
  background: #242b39;
  line-height: 40px;
  color: #fffefe;
  .topbarwarp {
    display: flex;
    justify-content: space-between;
    .left {
      font-size: 14px;
      font-weight: 300;
    }
    .right {
      li {
        float: left;
        margin-left: 20px;
        text-align: center;
        font-size: 14px;
        cursor: pointer;
        &.login-btn {
          width: 124px;
          background: #0a328e;
        }
        // 购物车
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
        //----
      }
      .avatar {
        width: 23px;
        height: 23px;
        border-radius: 50%;
        vertical-align: middle;
      }
    }
  }
}
</style>